<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      id="_id"
      title="组织"
      :data="treeFilterData"
      :default-value="initParam.condition.orgId"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        :indent="20"
        :highlight-current-row="true"
        row-key="_id"
        :columns="columns"
        :request-api="getTableList"
        :request-auto="false"
        :search-col="{ xs: 2, sm: 4, md: 4, lg: 5, xl: 5 }"
        :init-param="initParam"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
        </template>
        <template #roleIds="scope">
          <el-tag
            class="ml-2"
            v-for="(role, index) in scope.row.roleIds"
            :key="index"
            closable
            @close="roleDelete(scope.row, role)"
            >{{ role.name }}
          </el-tag>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="Plus" @click="settingRole(scope.row, true)">增加角色</el-button>
        </template>
      </ProTable>
      <CommonDialogSelect
        title="选择角色"
        :columns="roleColumns"
        :request-api="getRoleTableList"
        ref="drawerRef"
        @change="onRoleSelect"
      />
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { ExportObj, UserRole, UserRoles, Users } from "@/api/types/base";
import { Download } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { Plus } from "@element-plus/icons-vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import apiService from "@/api/services/apiService";
import CommonDialogSelect from "@/components/SelectFilter/common-dialog-select.vue";
import { dateRender } from "@/hooks/useColumnRender";
import { useDateFormat } from "@vueuse/core";
import { useDownload } from "@/hooks/useDownload";
import { ExportColType } from "@/enums/sysEnum";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDataStore } from "@/stores/modules/data";
const dataStore = useDataStore();
// ProTable 实例
const proTable = ref<ProTableInstance>();
const userRoleList = ref<UserRole[]>([]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  condition: { orgId: "" }
});

const getRoleTableList = (params: any) => {
  // let newParams = JSON.parse(JSON.stringify(params));
  return apiService.findTree("roles", params.condition, params.options);
};

onMounted(() => {
  getTreeList();
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  return new Promise(async resolve => {
    const users = await apiService.findPage<UserRoles>("users", params.condition, params.options);
    const userIds = users.data.content.map(item => item._id);
    const { data } = await apiService.find<UserRole[]>("userRoles", { userId: { $in: userIds } });

    const roles = await dataStore.findRoleList();
    const rolesMap = new Map();
    roles.forEach(role => rolesMap.set(role._id, role));

    userRoleList.value = data;
    const roleMap = new Map();
    data.forEach(item => {
      roleMap.has(item.userId) ? roleMap.get(item.userId).push(item.roleId) : roleMap.set(item.userId, [item.roleId]);
    });
    users.data.content.forEach(user => {
      let userRoleIds = roleMap.has(user._id) ? roleMap.get(user._id) : [];
      user.roleIds = [];
      if (userRoleIds && userRoleIds.length > 0) {
        userRoleIds.forEach(userRoleId => {
          if (rolesMap.has(userRoleId)) {
            user.roleIds.push(rolesMap.get(userRoleId));
          }
        });
      }
    });
    resolve(users);
  });
};

const treeFilterData = ref<any>([]);
const getTreeList = async () => {
  const { data } = await apiService.findTree("orgs", {}, { sort: { sort: 1 } });
  treeFilterData.value = data;
  initParam.condition.orgId = treeFilterData.value[0]._id;
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.condition.orgId = val;
};

// 表格配置项
const columns = reactive<ColumnProps<Users>[]>([
  { type: "index", label: " ", width: 60 },
  { prop: "userName", label: "用户名", search: { el: "input" }, width: 100 },
  {
    prop: "orgId",
    label: "所属组织",
    width: 200,
    // 字典请求携带参数
    enum: treeFilterData,
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "roleIds",
    label: "角色"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 表格配置项
const roleColumns: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 70 },
  { prop: "name", label: "角色", align: "left", search: { el: "input", like: true } },
  { prop: "createUser", label: "创建用户", width: 100 },
  { prop: "createDate", label: "创建时间", render: dateRender }
];

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `用户角色-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

const getExcelConfig = (): ExportObj => {
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  return {
    params: newParams,
    tableName: "users",
    keyPropName: "_id",
    enumTypes: ["SEX", "DATA_STATE"],
    tableConfigs: [
      { tableName: "orgs", fields: ["_id", "name"] },
      { tableName: "roles", fields: ["_id", "name"] },
      { tableName: "userRoles" }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      {
        header: "姓名",
        width: 8,
        ext: { prop: "userName", type: ExportColType.DEFAULT }
      },
      {
        header: "性别",
        width: 8,
        ext: { prop: "sex", type: ExportColType.ENUM, key: "SEX" }
      },
      { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
      { header: "邮箱", width: 30, ext: { prop: "email", type: ExportColType.DEFAULT } },
      { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "DATA_STATE" } },
      { header: "角色", width: 30, ext: { prop: "role", func: "roleProcess", type: ExportColType.CUSTOM } }
    ]
  };
};

const operateFalg = ref(true);
const curUser = ref<UserRoles>();
const drawerRef = ref<InstanceType<typeof CommonDialogSelect> | null>(null);
const settingRole = (row: UserRoles, flag: boolean) => {
  operateFalg.value = flag;
  curUser.value = row;
  drawerRef.value?.openDialog();
};

const roleDelete = async (row: any, role: any) => {
  curUser.value = row;
  if (curUser.value) {
    curUser.value.roleIds = curUser.value.roleIds.filter(item => item._id !== role._id);
    await apiService.deleteByCondition("userRoles", { userId: row._id, roleId: role._id });
    ElMessage.info(`角色【${role.name}】删除功能`);
  }
};

const onRoleSelect = async (roles: any) => {
  if (operateFalg.value) {
    const saveDocs: UserRole[] = [];
    roles.forEach(role => {
      if (curUser.value?.roleIds.indexOf(role._id) === -1) {
        curUser.value?.roleIds.push({ _id: role._id, name: role.name });
        saveDocs.push({
          userId: curUser.value?._id,
          roleId: role._id
        });
      }
    });
    apiService.saveList("userRoles", saveDocs);
  } else {
    let deleteIds: string[] = [];
    roles.forEach(role => {
      if (curUser.value?._id && curUser.value?.roleIds.indexOf(role._id) != -1) {
        curUser.value.roleIds = curUser.value.roleIds.filter(item => item !== role._id);
        userRoleList.value.forEach(item => {
          if (item.userId === curUser.value?._id && item.roleId === role._id && item._id) {
            deleteIds.push(item._id);
          }
        });
      }
    });
    apiService.deleteByCondition("userRoles", { _id: { $in: deleteIds } });
  }
};
</script>
